package com.yunti.yntk.activity.batchRecord;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.print.PrintAttributes;
import android.print.PrintManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.alibaba.fastjson.JSONObject;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.yunti.yntk.R;
import com.yunti.yntk.activity.BaseActivity;
import com.yunti.yntk.activity.updateScore.UpdateScoreActivity;
import com.yunti.yntk.activity.updateScore.UpdateScoreZxActivity;
import com.yunti.yntk.anotation.MyPrintAdapter;
import com.yunti.yntk.anotation.ViewInject;
import com.yunti.yntk.api.Result;
import com.yunti.yntk.api.req.ExportScoreReq;
import com.yunti.yntk.api.res.ExamBatchRes;
import com.yunti.yntk.api.res.ExamStuWithScore;
import com.yunti.yntk.api.res.RecordGroupsRes;
import com.yunti.yntk.manager.NetWorkManager;
import com.yunti.yntk.db.po.ExamStu;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class BatchRecordActivity extends BaseActivity {

    @ViewInject(R.id.batchRecordList)
    private ListView batchRecordListView;


    @ViewInject(R.id.checkStuListView)
    private ListView checkStuListView;

    @ViewInject(R.id.checkStuLayout)
    private FlexboxLayout checkStuLayout;

    @ViewInject(R.id.selectCheckStuLayout)
    private ConstraintLayout selectCheckStuLayout;

    @ViewInject(R.id.cancel_button)
    private TextView cancelButton;

    @ViewInject(R.id.confirm_button)
    private TextView confirmButton;

    @ViewInject(R.id.subNameView)
    private TextView subNameView;

    @ViewInject(R.id.printlist_button)
    private TextView printListButton;

    @ViewInject(R.id.batchSpinner)
    private Spinner batchSpinner;

    @ViewInject(R.id.sexSpinner)
    private Spinner sexSpinner;

    @ViewInject(R.id.screen_button)
    private TextView screenButton;

    private List<RecordGroupsRes> batchRecordeList = new ArrayList<>();
    private List<ExamStu> examStuBeanArrayList = new ArrayList<>();

    private ArrayList<String> listForSpinner;
    private ArrayAdapter<String> adapterForSpinner;

    private ArrayList<String> sexListForSpinner;
    private ArrayAdapter<String> adapterForSexSpinner;

    @ViewInject(R.id.empty)
    private ImageView empty;

    @ViewInject(R.id.refreshButton)
    private FloatingActionButton refreshButton;
    private RecordeItemAdapter batchRecordeItemAdapter;
    private CheckStuItemAdapter checkStuItemAdapter;
    private String subName;
    private Integer subId;

    private Integer sex;

    private int type;


    private RecordGroupsRes selectBatchRecordRes;

    private List<ExamBatchRes> examBatchResList = new ArrayList<>();

    @Override
    public int initLayoutId() {
        return R.layout.activity_batchrecord;
    }

    @Override
    public void initView() {
        batchRecordeItemAdapter = new RecordeItemAdapter(this, R.layout.item_recorditemlist, batchRecordeList);
        batchRecordListView.setAdapter(batchRecordeItemAdapter);

        checkStuItemAdapter = new CheckStuItemAdapter(this, R.layout.item_recorditemlist, examStuBeanArrayList);
        checkStuListView.setAdapter(checkStuItemAdapter);

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                examStuBeanArrayList.clear();
                checkStuItemAdapter.notifyDataSetChanged();
                selectCheckStuLayout.setVisibility(View.INVISIBLE);
            }
        });

        printListButton.setOnClickListener(this::printListButton);

        confirmButton.setOnClickListener(this::confirmGroup);
        screenButton.setOnClickListener(this::showScreen);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getBatchRecords();
            }
        });

    }

    private void showScreen(View view) {
//        new Thread(() -> {
//            Call<Result> call = NetWorkManager.getRequest().showData(this.selectBatchRecordRes);
//            try {
//                call.execute();
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }).start();
    }


    @Override
    public void initData() throws IOException {
        Intent intent = getIntent();
        subName = intent.getStringExtra("subName");
        subId = intent.getIntExtra("subId", 0);
        type = intent.getIntExtra("type", 1);
        if (subName == null) {
            subName = "跳远";
        }
        subNameView.setText(subName);

        listForSpinner = new ArrayList<>();
        adapterForSpinner = new ArrayAdapter<>(this, R.layout.item_for_custom_spinner, listForSpinner);
        batchSpinner.setAdapter(adapterForSpinner);
        batchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                getBatchRecords();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        sexListForSpinner = new ArrayList<>();
        sexListForSpinner.add("男子组");
        sexListForSpinner.add("女子组");
        adapterForSexSpinner = new ArrayAdapter<>(this, R.layout.item_for_custom_spinner, sexListForSpinner);
        sexSpinner.setAdapter(adapterForSexSpinner);
        sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (l == 0) {
                    sex = 1;
                }
                if (l == 1) {
                    sex = 2;
                }
                if(batchIsInit){
                    getBatchRecords();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


//        getBatchRecords();
        empty.setVisibility(View.GONE);
        checkStuLayout.setVisibility(View.VISIBLE);
        getBatchList();
    }

    boolean batchIsInit = false;
    private void getBatchList() {
        Call<Result<List<ExamBatchRes>>> call = NetWorkManager.getRequest().getBatchList();
        call.enqueue(new Callback<Result<List<ExamBatchRes>>>() {
            @Override
            public void onResponse(Call<Result<List<ExamBatchRes>>> call, Response<Result<List<ExamBatchRes>>> response) {
                Result<List<ExamBatchRes>> result = response.body();
                if (result != null && result.getCode() == 200) {
                    List<ExamBatchRes> localExamBatchResList = result.getData();
                    examBatchResList.clear();
                    for (int i = 0; i < localExamBatchResList.size(); i++) {
                        examBatchResList.add(localExamBatchResList.get(i));
                    }


                    List<String> batchList = new ArrayList<>();
                    for (int i = 0; i < examBatchResList.size(); i++) {
                        batchList.add(examBatchResList.get(i).getBatchName());
                    }
                    listForSpinner.clear();
                    listForSpinner.addAll(batchList);

                    runOnUiThread(() -> {
                        adapterForSpinner.notifyDataSetChanged();
                        for (int i = 0; i < examBatchResList.size(); i++) {
                            if (type == 1 && Integer.valueOf(1).equals(examBatchResList.get(i).getBatchStatus())) {
                                batchSpinner.setSelection(i);
                            }
                            if (type == 2 && Integer.valueOf(1).equals(examBatchResList.get(i).getSpecialStatus())) {
                                batchSpinner.setSelection(i);
                            }
                        }
                        checkStuLayout.setVisibility(View.VISIBLE);
                        empty.setVisibility(View.GONE);
                        batchIsInit = true;
                    });
                }
            }

            @Override
            public void onFailure(Call<Result<List<ExamBatchRes>>> call, Throwable t) {

            }
        });

    }


    public void back(View view) {
        this.finish();
    }

    private void getBatchRecords() {
//        if (examBatchResList == null) {
//            runOnUiThread(() -> {
//                mPullRefreshLayout.finishRefresh();
//            });
//            return;
//        }
        new Thread(() -> {
            JSONObject req = new JSONObject();
            req.put("subId", subId);
            req.put("sex", sex);
            req.put("batch", examBatchResList.get(batchSpinner.getSelectedItemPosition()).getId());
            Call<Result<List<RecordGroupsRes>>> call = NetWorkManager.getRequest().getRecordGroups(req);
            call.enqueue(new Callback<Result<List<RecordGroupsRes>>>() {
                @Override
                public void onResponse(Call<Result<List<RecordGroupsRes>>> call, Response<Result<List<RecordGroupsRes>>> response) {
                    Result<List<RecordGroupsRes>> result = response.body();
                    batchRecordeList.clear();
                    if (result.getData() != null && result.getData().size() != 0) {
                        batchRecordeList.addAll(result.getData());
                        runOnUiThread(() -> {
                            empty.setVisibility(View.GONE);
                            checkStuLayout.setVisibility(View.VISIBLE);
                        });
                    }
                    runOnUiThread(() -> {
                        batchRecordeItemAdapter.notifyDataSetChanged();
                    });
                }

                @Override
                public void onFailure(Call<Result<List<RecordGroupsRes>>> call, Throwable t) {
                    runOnUiThread(() -> {
                        batchRecordeList.clear();

                        batchRecordeItemAdapter.notifyDataSetChanged();
                    });
                }
            });
        }).start();
    }


    class RecordeItemAdapter extends ArrayAdapter<RecordGroupsRes> {
        public RecordeItemAdapter(@NonNull Context context, int resource, @NonNull List<RecordGroupsRes> objects) {
            super(context, resource, objects);
        }


        //每个子项被滚动到屏幕内的时候会被调用
        @SuppressLint("SetTextI18n")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            RecordGroupsRes batchRecordRes = getItem(position);//得到当前项的 Fruit 实例
            //为每一个子项加载设定的布局
            @SuppressLint("ViewHolder")
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_recorditemlist, parent, false);
            //分别获取 image view 和 textview 的实例
            TextView pc = view.findViewById(R.id.pc);
            TextView zh = view.findViewById(R.id.zh);
            TextView name = view.findViewById(R.id.name);
            TextView stuNum = view.findViewById(R.id.stuNum);

            pc.setText(batchRecordRes.getGroupId() + "");
            zh.setText(batchRecordRes.getGroupId() + "");
            name.setText(subName + "第" + batchRecordRes.getGroupId() + "组");
            if (batchRecordRes.getCount() != null) {
                stuNum.setText(batchRecordRes.getCount() + "");
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showStudentList(batchRecordRes);
                }
            });
            return view;
        }
    }

    class CheckStuItemAdapter extends ArrayAdapter<ExamStu> {
        public CheckStuItemAdapter(@NonNull Context context, int resource, @NonNull List<ExamStu> objects) {
            super(context, resource, objects);
        }


        //每个子项被滚动到屏幕内的时候会被调用
        @SuppressLint("SetTextI18n")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ExamStu examStuBean = getItem(position);//得到当前项的 Fruit 实例
            //为每一个子项加载设定的布局
            @SuppressLint("ViewHolder")
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_checkstu, parent, false);
            //分别获取 image view 和 textview 的实例

            ImageView photo = view.findViewById(R.id.photo);
            TextView no = view.findViewById(R.id.no);
            TextView name = view.findViewById(R.id.name);
            TextView sex = view.findViewById(R.id.sex);
            TextView scoreText = view.findViewById(R.id.scoreText);
            no.setText(examStuBean.getExamNum() + "");
            name.setText(examStuBean.getStuName() + "");

            if (subId == 2) {
                scoreText.setText(examStuBean.getJumpScore());
            } else if (subId == 3) {
                scoreText.setText(examStuBean.getShotScore());
            } else if (subId > 3) {
                scoreText.setText(examStuBean.getSpecialScore());
            }


            if (examStuBean.getSex() != null) {
                sex.setText(examStuBean.getSex().equals(1) ? "男" : "女");
            }

            new Thread(() -> {
                Bitmap bitmap = null;
//                if (examStuBean.getPhoto() != null) {
//                    bitmap = BitmapUtils.getBitmapByurl(ConfigManager.getInstance().getApiAddress() + examStuBean.getPhoto());
//                }

                if (bitmap != null) {
                    Bitmap finalBitmap = bitmap;
                    runOnUiThread(() -> {
                        photo.setImageBitmap(finalBitmap);
                    });
                } else {
                    if (examStuBean.getSex() == null || examStuBean.getSex().equals(1)) {
                        runOnUiThread(() -> {
                            photo.setImageResource(R.mipmap.boy);
                        });
                    } else {
                        runOnUiThread(() -> {
                            photo.setImageResource(R.mipmap.girl);
                        });
                    }

                }
            }).start();
            return view;
        }
    }


    private void showStudentList(RecordGroupsRes batchRecordRes) {
        this.selectBatchRecordRes = batchRecordRes;
        selectCheckStuLayout.setVisibility(View.VISIBLE);
        examStuBeanArrayList.clear();
        JSONObject req = new JSONObject();
        req.put("subId", subId);
        req.put("groupId", batchRecordRes.getGroupId());
        req.put("sex", sex);
        req.put("batch", examBatchResList.get(batchSpinner.getSelectedItemPosition()).getId());
        Call<Result<List<ExamStu>>> call = NetWorkManager.getRequest().getBatchRecords(req);
        call.enqueue(new Callback<Result<List<ExamStu>>>() {
            @Override
            public void onResponse(Call<Result<List<ExamStu>>> call, Response<Result<List<ExamStu>>> response) {
                Result<List<ExamStu>> result = response.body();
                examStuBeanArrayList.clear();
                if (result.getData() != null && result.getData().size() != 0) {
                    examStuBeanArrayList.addAll(result.getData());
                }
                runOnUiThread(() -> {
                    checkStuItemAdapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onFailure(Call<Result<List<ExamStu>>> call, Throwable t) {
                runOnUiThread(() -> {
                    checkStuItemAdapter.notifyDataSetChanged();
                });
            }
        });


    }

    private void confirmGroup(View view) {
        System.out.println("确认");
        if(subId==2){
            Intent intent = intent = new Intent(this, UpdateScoreActivity.class);
            intent.putExtra("subId", subId);
            intent.putExtra("subName", subName);
            intent.putExtra("sex", sex);
            intent.putExtra("groupId", selectBatchRecordRes.getGroupId());
            intent.putExtra("batch", examBatchResList.get(batchSpinner.getSelectedItemPosition()).getId());
            startActivity(intent);
        }else{
            Intent intent = intent = new Intent(this, UpdateScoreZxActivity.class);
            intent.putExtra("subId", subId);
            intent.putExtra("subName", subName);
            intent.putExtra("sex", sex);
            intent.putExtra("groupId", selectBatchRecordRes.getGroupId());
            intent.putExtra("batch", examBatchResList.get(batchSpinner.getSelectedItemPosition()).getId());
            startActivity(intent);
        }

    }

    private void printListButton(View v) {
        printScore();
    }

    public void printScore() {
        if (true) {
            ExportScoreReq exportScoreReq = new ExportScoreReq();
            exportScoreReq.setBatch(examBatchResList.get(batchSpinner.getSelectedItemPosition()).getId());
            exportScoreReq.setSex(sex);
            exportScoreReq.setSubId((long) subId);
            exportScoreReq.setGroupId((long) selectBatchRecordRes.getGroupId());
            Call<ResponseBody> call = NetWorkManager.getRequest().exportScore(exportScoreReq);

            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    runOnUiThread(() -> {
                        Toast.makeText(BatchRecordActivity.this, "网络请求成功", Toast.LENGTH_LONG);
                    });
                    if (response.isSuccessful()) {
                        // 文件下载成功
                        runOnUiThread(() -> {
                            Toast.makeText(BatchRecordActivity.this, "网络请求失败", Toast.LENGTH_LONG);
                        });
                        saveFile(response.body());
                    } else {
                        // 文件下载失败
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    // 网络请求失败
                    runOnUiThread(() -> {
                        Toast.makeText(BatchRecordActivity.this, "网络请求失败", Toast.LENGTH_LONG);
                    });

                }
            });
        }

    }

    private void saveFile(ResponseBody body) {
        try {
            File scorePdfDir = getBaseContext().getExternalFilesDir("scorePdf");
            if (!scorePdfDir.exists()) {
                scorePdfDir.mkdir();
            }
            File file = new File(scorePdfDir, "成绩单.pdf");


            if (file.exists()) {
                file.delete();
            }

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(file);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                }

                outputStream.flush();
                // 文件下载成功
                runOnUiThread(() -> {
                    Toast.makeText(BatchRecordActivity.this, "文件存储成功：" + file.getPath(), Toast.LENGTH_LONG);
                });
            } catch (IOException e) {
                // 保存文件失败
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }

                onPrintPdf(file.getPath());
            }
        } catch (IOException e) {
            // 保存文件失败
        }
    }

    private void onPrintPdf(String filePath) {
        PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
        PrintAttributes.Builder builder = new PrintAttributes.Builder();
        builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
        printManager.print("test pdf print", new MyPrintAdapter(this, filePath), builder.build());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (examBatchResList != null && examBatchResList.size() > 0) {
            getBatchRecords();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int i = 0; i < batchRecordeList.size(); i++) {
                if (batchRecordeList.get(i).getGroupId() != null && batchRecordeList.get(i).getGroupId() == selectBatchRecordRes.getGroupId()) {
                    showStudentList(batchRecordeList.get(i));
                }
            }

        }
    }

}
